using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MQTTnet.AspNetCore;
using MQTTnet.AspNetCore.Extensions;
using MQTTnet.Protocol;
using System.Linq;

namespace MQTT.Broker
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            Config.UserName = Configuration["MqttOption:UserName"];
            Config.Pwd = Configuration["MqttOption:Password"];

            services.AddHostedMqttServer(mqttServer => mqttServer.WithoutDefaultEndpoint().WithConnectionValidator(c =>
            {
                if (Config.UserName != null && Config.Pwd != null)
                {
                    if (c.Username != Config.UserName || c.Password != Config.Pwd)
                    {
                        c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
                        return;
                    }
                }
                c.ReasonCode = MqttConnectReasonCode.Success;

            }))
             .AddMqttConnectionHandler()
             .AddConnections();

            services.AddControllers();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();


            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapConnectionHandler<MqttConnectionHandler>(
             "/mqtt",
             httpConnectionDispatcherOptions => httpConnectionDispatcherOptions.WebSockets.SubProtocolSelector =
                                                    protocolList =>
                                                        protocolList.FirstOrDefault() ?? string.Empty);
            });
            app.UseMqttServer(S =>
            {
                MqttHelper.Server = S;
            });
        }
    }
}
